package com.vma.tools;

import sun.misc.BASE64Encoder;

import javax.crypto.KeyGenerator;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by chenzui on 2017/5/6.
 */
public class Encrypt {


    private final byte[] keybyte="1A1FBDD13082FF4722F12783".getBytes(); //keybyte为加密密钥，长度为24字节
    /**
     * 加密方法提供3des加密，并且base64编码
     * @param key 24字节的密钥
     * @param str 明文
     * @return
     */
    public static String DataEncrypt(byte[] key, String str ) {
        String encrypt = null;
        try {
            byte[] ret = ThreeDes.encryptMode(key,str.getBytes("UTF-8"));
            encrypt = new String(Base64Util.encode(ret));
        } catch (Exception e) {
            System.out.print(e);
            encrypt = str;
        }
        return encrypt;
    }
    /***
     * 解密方法，先解密base64,在按3des解密
     * @param key 24字节的密钥
     * @param str 密文
     * @return
     */
    public static String DataDecrypt(byte[] key,String str ) {
        String decrypt = null;
        try {
            byte[] ret = ThreeDes.decryptMode( key,Base64Util.decode(str));
            decrypt = new String(ret, "UTF-8");
        } catch (Exception e) {
            System.out.print(e);
            decrypt = str;
        }
        return decrypt;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        KeyGenerator kg = KeyGenerator.getInstance("DESede");
        kg.init(168);//must be equal to 112 or 168
        System.out.println("SecretKey:");
        String key = new BASE64Encoder().encode(kg.generateKey().getEncoded()).substring(0,24);
        System.out.println(key);
        byte[] keybyte="x/fBeYXQ95Q+Aa7QGYVigzRD".getBytes();


//        String t = String.valueOf(System.currentTimeMillis());
        String t = "1496318030205";
        System.out.println("原始字符串："+t);
        String md5Str = MD5Helper.getMD5Str(t);
        System.out.println("MD5字符串："+md5Str);

        //加密后的字符串
        String res = Encrypt.DataEncrypt(keybyte,md5Str);
        System.out.println("最终加密后的字符串"+res);
        String de = Encrypt.DataDecrypt(keybyte,res);
        System.out.println(de);
    }
}
